package com.yuliang.ai.config;


import com.alibaba.fastjson.JSONObject;
import com.yuliang.ai.domain.Dto.AreaDto;
import com.yuliang.ai.request.SocketIOClientLaunch;
import com.yuliang.ai.service.HotelService;
import com.yuliang.utils.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Huangkai
 */
@Slf4j
@Component
public class CommandLineRunnerConfig implements CommandLineRunner {

    @Autowired
    SocketIOClientLaunch socketIOClientLaunch;

    @Autowired
    HotelService hotelService;

    @Value("${spring.sensitiveWordFilePath}")
    private String sensitiveWordFilePath;

    @Override
    public void run(String... args) {
        RedisUtils.delete("token");
        socketIOClientLaunch.clientSocketIo();
        //onload(sensitiveWordFilePath);
        List<AreaDto> areaDtoList = hotelService.selectCityList();
        initCity(areaDtoList);


        /*
        List<AreaDto> areaDtoList = jsonArray.toJavaList(AreaDto.class);
        AreaDto areaDto = areaDtoList.get(0);
        log.info("获取值{}", areaDto);
        initCity(areaDtoList);

         */
    }

    public void onload(String filePath) {
        /*
        List<String> keywordList = new ArrayList<>();
        try{
            File fin = new File(filePath);
            FileInputStream fis = new FileInputStream(fin);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

            String line;
            while ((line = br.readLine()) != null) {
                keywordList.add(line);
                System.out.println(line);
            }
            RedisUtils.set(RedisConf.sensitiveWordListKey, JSONObject.toJSONString(keywordList));
            br.close();
            fis.close();
        }catch (Exception exception){
            exception.printStackTrace();
        }

         */
    }

    public void initCity(List<AreaDto> areaDtoList){
        AreaDto areaDto = areaDtoList.stream().findFirst().get();
        List<AreaDto> childrenList = areaDto.getChildrenList();
        Map<String, AreaDto> areaDtoMap = childrenList.stream().collect(Collectors.groupingBy(AreaDto::getValue,
                Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
        for(Map.Entry<String, AreaDto> entry : areaDtoMap.entrySet()){
            String city = entry.getKey();
            AreaDto getAreaDto = entry.getValue();
            RedisUtils.set(city, JSONObject.toJSONString(getAreaDto));
        }

    }
}
